<template>
  <div>
    <div
      style="display: flex; align-items: center; justify-content: space-between"
    >
      <div>
        <el-button type="info" size="small" link>
          <!-- <el-icon><InfoFilled /></el-icon> -->
          <span>席位数:</span>
          <b>{{ summaryData.seatCount }}</b>
          <span style="padding: 0 3px"></span>
          <span>移交次数:</span>
          <b>{{ summaryData.totalValue }}</b>
          <span style="padding: 0 6px; opacity: 0.5; font-weight: bold">|</span>
          <span>平均架次:</span>
          <b>{{ summaryData.averageValue }}</b>
          <span style="padding: 0 3px"></span>
          <span>最高架次:</span>
          <b>{{ summaryData.maxValue }}</b>
          <span style="padding: 0 3px"></span>
          <!-- <span>席位:</span> -->
          <span>@</span>
          <b>{{ summaryData.maxSeat }}</b>
          <span style="padding: 0 6px; opacity: 0.5; font-weight: bold">|</span>
          <span>平均负荷:</span>
          <b>{{ summaryData.averageLoad }}</b>
          <span style="padding: 0 3px"></span>
          <span>最高负荷:</span>
          <b>{{ summaryData.maxLoad }}</b>
          <span style="padding: 0 3px"></span>
          <!-- <span>席位:</span> -->
          <span>@</span>
          <b>{{ summaryData.busySeat }}</b>
          <span style="padding: 0 3px"></span>
        </el-button>
      </div>
      <div>
        <el-button
          link
          type="info"
          icon="Refresh"
          @click="refreshGraphic()"
        ></el-button>
        <el-button
          link
          type="info"
          icon="Document"
          @click="showRawData()"
        ></el-button>
        <el-button
          type="info"
          link
          @click="download()"
          icon="Download"
        ></el-button>
      </div>
    </div>
    <svg id="graphic" class="graphic" :viewBox="viewBox" v-if="showGraphic">
      <g>
        <polygon
          v-for="polygon in SectorGraphicData.polygons"
          class="area-default"
          :points="polygon.points"
          :style="{ fill: matchColor(polygon.id) }"
        ></polygon>
      </g>
      <g>
        <g v-for="seat in arrangedData">
          <g
            v-for="center in seat.centers"
            :transform="`translate(${center.x} ${center.y})`"
          >
            <text class="text-default" transform="translate(-8 -56)">
              {{ seat.seat }}
            </text>
            <text class="text-default text-small" transform="translate(0 -8)">
              架次:
            </text>
            <text class="text-default" transform="translate(96 0)">
              {{ seat.value }}
            </text>
            <text class="text-default text-small" transform="translate(0 48)">
              负荷:
            </text>
            <text class="text-default" transform="translate(96 56)">
              {{ seat.load }}
            </text>
            <!-- <text
              class="text-default text-mini"
              :transform="`translate(${center.x} ${center.y + 60})`"
            >
              {{ seat.sector.join(" ") }}
            </text> -->
          </g>
        </g>
      </g>
    </svg>
  </div>
  <!-- <pre>{{ arrangedData }}</pre> -->
</template>

<script setup>
import { h, ref, computed, nextTick, watch, onMounted, onUnmounted } from "vue";
import { ElMessageBox, ElInput } from "element-plus";
import SectorGraphicData from "./SectorGraphicData.json";
import useCommonStore from "@/store/common.js";
import useFlowStore from "@/store/flow.js";

const commonStore = useCommonStore();
const flowStore = useFlowStore();

const Props = defineProps({
  seatData: {
    type: Array,
    required: true,
  },
  // sectorScheme: {
  //   type: Array,
  //   required: true,
  // },
});

const viewBox = ref(SectorGraphicData.viewBox);

const showGraphic = ref(true);
const refreshGraphic = async () => {
  showGraphic.value = false;
  setTimeout(() => {
    showGraphic.value = true;
  }, 200);
};

const showRawData = () => {
  ElMessageBox({
    title: "席位数据",
    message: h(
      "pre",
      {
        style: {
          fontFamily: "Consolas",
          fontSize: "12",
          height: "320px",
          overflow: "auto",
        },
      },
      JSON.stringify(arrangedData.value, null, 2)
    ),
  });
};

const download = () => {
  let dataURL =
    "data:image/svg+xml;charset=UTF-8," +
    encodeURI(
      new XMLSerializer().serializeToString(document.getElementById("graphic"))
    );
  // console.log("dataURL", dataURL);
  const elink = document.createElement("a");
  elink.download = "sectorData.svg"; // 设置默认文件名
  elink.style.display = "none";
  elink.href = dataURL;
  document.body.appendChild(elink);
  elink.click();
  URL.revokeObjectURL(elink.href); // 释放URL 对象
  document.body.removeChild(elink);
};

const matchColor = (code) => {
  let color = "rgba(128,128,128,0.5)";
  Props.seatData.forEach((cell, index) => {
    if (cell.seat == code || cell.sector.includes(code)) {
      if (commonStore.darkMode) {
        color = flowStore.seatColors[cell.seat][0];
      } else {
        color = flowStore.seatColors[cell.seat][1];
      }
    }
  });
  return color;
};

const sectors = computed(() => {
  let data = {};
  for (let i = 0; i < SectorGraphicData.polygons.length; i++) {
    let code = SectorGraphicData.polygons[i].id;
    let z = SectorGraphicData.polygons[i].z;
    let g = SectorGraphicData.polygons[i].g;
    let points = SectorGraphicData.polygons[i].points.split(" ");
    let p = new Array();
    for (let j = 0; j < points.length; j += 2) {
      p.push({ x: Number(points[j]), y: Number(points[j + 1]) });
    }
    data[code] = { p, z, g };
  }
  return data;
});

const arrangedData = computed(() => {
  let data = new Array();
  for (let i = 0; i < Props.seatData.length; i++) {
    let seat = JSON.parse(JSON.stringify(Props.seatData[i]));
    // seat.points = new Array();
    seat.centers = new Array();
    let ranges = [
      { v: false, t: 0, r: 0, b: 0, l: 0 },
      { v: false, t: 0, r: 0, b: 0, l: 0 },
      { v: false, t: 0, r: 0, b: 0, l: 0 },
    ];
    // seat.z = 0;
    seat.sector.forEach((item, index) => {
      // console.log("MMM", item, sectors.value);
      // if (seat.z < sectors.value[item].z) seat.z = sectors.value[item].z;
      // let p = "";
      if (sectors.value[item]) {
        sectors.value[item].p.forEach((point) => {
          // p += point.x.toFixed(2) + " " + point.y.toFixed(2) + " ";
          let range = ranges[sectors.value[item].g];
          if (range.t > point.y || !range.v) {
            range.t = point.y;
          }
          if (range.b < point.y || !range.v) {
            range.b = point.y;
          }
          if (range.l > point.x || !range.v) {
            range.l = point.x;
          }
          if (range.r < point.x || !range.v) {
            range.r = point.x;
          }
          range.v = true;
        });
      }

      // seat.points.push({ z: sectors.value[item].z, p });
    });
    ranges.forEach((item, index) => {
      // console.log("@20240123", item, index);
      if (item.v) {
        let x = Number((0.5 * (item.r + item.l)).toFixed(2));
        let y = Number((0.5 * (item.t + item.b)).toFixed(2));
        seat.centers.push({ x, y });
      }
    });
    // seat.points.sort((a, b) => a.z - b.z);
    data.push(seat);
  }
  // data.sort((a, b) => a.z - b.z);
  return data;
});

const gaugeData = computed(() => {
  let data = [];
  for (let i = 0; i < Props.seatData.length; i++) {
    let cell = Props.seatData[i];
    let name = cell.seat;
    let value = cell.value;
    let load = cell.load;
    data.push({ name, value, load });
  }
  return data;
});

const summaryData = computed(() => {
  let maxSeat = "";
  let maxValue = 0;
  let totalValue = 0;
  let maxLoad = 0;
  let busySeat = "";
  let totalLoad = 0;
  let seatCount = gaugeData.value.length;
  for (let i = 0; i < seatCount; i++) {
    let cell = gaugeData.value[i];
    totalValue += cell.value;
    totalLoad += cell.load;
    if (cell.value > maxValue) {
      maxValue = cell.value;
      maxSeat = cell.name;
    }
    if (cell.load > maxLoad) {
      maxLoad = cell.load;
      busySeat = cell.name;
    }
  }
  let averageValue = Math.round(totalValue / seatCount);
  let averageLoad = Math.round(totalLoad / seatCount);
  return {
    seatCount,
    maxSeat,
    maxValue,
    averageValue,
    totalValue,
    maxLoad,
    busySeat,
    averageLoad,
  };
});
</script>

<style scoped>
.graphic {
  transition: all 0.3s ease-in-out;
  margin-top: 24px;
}
.area-default {
  stroke: rgba(0, 0, 0, 0.25);
  stroke-width: 2;
  opacity: 0.75;
  transition: all 0.3s ease-in-out;
  cursor: pointer;
}

.area-default:hover {
  opacity: 1;
}

.text-default {
  fill: #fff;
  font-family: Consolas;
  font-weight: bold;
  font-size: 64px;
  /* font-size: 24px; */
  text-shadow: 0 0 2px #000, 0 0 4px #000, 0 0 16px #000;
  user-select: none;
  cursor: pointer;
  text-anchor: start;
  text-align: left;
}
.text-medium {
  font-size: 48px;
}

.text-small {
  font-size: 32px;
}
.text-mini {
  font-size: 16px;
  font-weight: normal;
}
</style>
